package com.training.admin.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.persistence.annotation.Dao;
import com.training.admin.dao.PrincipalDao;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;

/**
 * 
 * @author dan
 *
 */
@Service("principalService")
public class PrincipalServiceImpl extends DataServiceImpl<Principal> implements PrincipalService{
    
    @Dao
    private PrincipalDao principalDao;
    
    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.authority.PrincipalService#count(com.fita.admin.entity.security.Login)
     */
    public int count(Login login) {
        return principalDao.count();
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.authority.PrincipalService#list(com.fita.admin.entity.security.Login, com.demo2do.core.entity.page.Page)
     */
    public List<Principal> list(Login login, Page page) {
        return principalDao.listByPage(page.getBeginIndex(), page.getMaxResultRecords());
    }

    /*
     * (non-Javadoc)
     * @see com.training.admin.service.authority.PrincipalService#loadByName(String)
     */
	public Principal loadByName(String username) {
		 return principalDao.load(username);
	}
	public Principal loadByEmail(String username) {
		 return principalDao.loadByEmail(username);
	}

	/* (non-Javadoc)
	 * @see com.training.admin.service.PrincipalService#create(com.training.admin.entity.principal.Principal)
	 */
	@Override
	public void create(Principal principal) {
    	// 1. check user loginName
    	int existLoginName = principalDao.countByEmail(principal.getEmail());
    	if (existLoginName > 0) {
    		throw BusinessException.newInstance("400", "该邮箱已存在");
    	}
    	
    	if(principal.getAuthority().equals("ROLE_SUPER_USER")) {
    	    principal.setDepartmentId(null);
    	}
    	
    	// 2. save user
    	String password = principal.getPassword();
        genericDaoSupport.save(principal.init(new Date()).changePassword(password));
	}

	/* (non-Javadoc)
	 * @see com.training.admin.service.PrincipalService#resetPassword(com.training.admin.entity.principal.Principal, java.lang.String)
	 */
	@Override
	public void resetPassword(Principal principal, String password) {
		genericDaoSupport.update(principal.changePassword(password).update(new Date()));
	}
    

}
